<?php

namespace app\commons;

use Yii;
use yii\filters\auth\AuthMethod;
use yii\helpers\Json;

/**
 * sign 验证类
 */
class SignFilter extends AuthMethod
{

    const PRIVATE_KEY = '12345678';
    public $signParam = 'sign';
    public $timeParam = 'ut';
    private $ignoreParams = ['r'];

    const TIME_LOSE = '600';

    /**
     * {@inheritdoc}
     */
    public function authenticate($user, $request, $response)
    {
        $sign = $request->get($this->signParam);
        $utc = $request->get($this->timeParam);

        if (is_string($sign)) {
            if(!$this->checkSign($sign,$utc))
            {
                $this->handleFailure($response);
            }
            return true;
        }

        if ($sign !== null) {
            $this->handleFailure($response);
        }
        return null;
    }

    private function checkSign($sign,$utc)
    {
        if( (gmdate('U')-$utc) > self::TIME_LOSE )
        {
            return false;
        }
        return $this->getSign() === $sign;

    }

    public function getSign()
    {

        $params = $this->getGetParams();
        $key = implode(',', $params);
        $raw = Yii::$app->request->getRawBody();
        return md5(self::PRIVATE_KEY . md5($key) . md5($raw) ) ;
    }

    public function getGetParams()
    {
        $getParams = Yii::$app->request->get();

        unset($getParams[$this->signParam]);
        foreach($this->ignoreParams as $param)
        {
            unset($getParams[$param]);
        }
        ksort($getParams);
        return $getParams;
    }

    public function getRaw()
    {
        $raw = Yii::$app->request->getRawBody();
        return Json::decode($raw);
    }


}